import {encrypt,decrypt} from "@/utils";
// ES
import * as RongIMLib from "@rongcloud/imlib-next";
import pako from "pako";
import { Toast } from "vant";
// byte数组转码Uint8Array
// function wordArrayToUint8(array, length = array.length * 4) {
//   var bin = new Uint8Array(Math.min(array.length * 4, length));
//   for (var i = 0; i < array.length; i++) {
//     var num = array[i];
//     if (num < 0) {
//       num = array[i] + 0x100000000;
//     }
//     bin[i * 4 + 0] = (num >>> 24) & 0xff;
//     bin[i * 4 + 1] = (num >>> 16) & 0xff;
//     bin[i * 4 + 2] = (num >>> 8) & 0xff;
//     bin[i * 4 + 3] = (num >>> 0) & 0xff;
//   }
//   return bin;
// }
// 解压
function gunzip(binData) {
  var data = pako.inflate(new Uint8Array(binData));
  var jsonStr = Utf8ArrayToStr(data);
  return jsonStr;
}
// Uint8Array数组转码字符串
function Utf8ArrayToStr(array) {
  var out, i, len, c;
  var char2, char3;
  out = "";
  len = array.length;
  i = 0;
  while (i < len) {
    c = array[i++];
    switch (c >> 4) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12:
      case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(
          ((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0)
        );
        break;
    }
  }
  return out;
}

// base64转码byte[]
// function _base64ToArrayBuffer(base64) {
//   var binary_string = window.atob(base64); //解码使用base64编码的字符串
//   var len = binary_string.length; //获取长度
//   var bytes = new Uint8Array(len);
//   for (var i = 0; i < len; i++) {
//     bytes[i] = binary_string.charCodeAt(i);
//   }
//   return bytes.buffer;
// }
// const isObject = (obj) =>
//   Object.prototype.toString.call(obj) === "[object Object]";
// const isArray = (obj) =>
//   Object.prototype.toString.call(obj) === "[object Array]";

let countRefresh = 0;
class RySocket {
  constructor(store, router, bus) {
    // vue store
    this.$store = store;
    // vue router
    this.$router = router;
    // vue event bus
    this.$bus = bus;
    // 是否已经连接成功
    this.isConnected = false;
    // 当前房间
    this.roomNo = "";
    this.roomNoFlag = true;
    // 重连时间
    this.timeOut = 5000;
    // 重连
    this.timer = null;
    // 多端登录
    this.timer3 = null;
    this.hasMsg = false;
    // 手动断开
    this.ownClose = false;
  }
  // 反初始化
  destroy() {
    RongIMLib.destroy();
  }
  // 初始化融云
  init() {
    // 应用初始化以获取 RongIMLib 实例对象，请务必保证此过程只被执行一次
    const ay = this.$store.loginUserInfo.ay;
    console.log(ay)
    if (
      this.$store.loginUserInfo.appType &&
      this.$store.loginUserInfo.appType==='1'
    ) {
      RongIMLib.init({
        appkey: ay,
        navigators: [
          "https://nav.sg-light-edge.com",
          "https://nav-b.sg-light-edge.com",
        ],
      });
    } else {
      RongIMLib.init({ appkey: ay });
    }
    const Events = RongIMLib.Events;
    console.log(Events);
    /**
     * 正在链接的事件状态
     */
    RongIMLib.addEventListener(Events.CONNECTING, () => {
      console.log("正在链接...");
    });

    /**
     * 链接到服务器会触发这个事件
     */
    RongIMLib.addEventListener(Events.CONNECTED, () => {
      console.log("连接成功");
      this.ownClose = false;
      this.isConnected = true;
	  this.$store.saveSocketIsConnected(true);
      // 如果有重连timer 清理重连timer
      if (this.timer) {
        clearInterval(this.timer);
      }
    });

    /**
     * 手动调用 disconnect 方法或者用户被踢下线 会触发这个事件
     */
    RongIMLib.addEventListener(Events.DISCONNECT, (ErrorCode) => {
      console.log("连接中断", ErrorCode);
      if (ErrorCode !== 2) {
        Toast.warning("连接中断," + ErrorCode);
      }
      if (ErrorCode === 31010) {
        if (this.timer3) {
          clearInterval(this.timer3);
        }
        this.timer3 = setTimeout(() => {
          Toast({
            message: "连接已断开，请重新登录",
            duration: 3000,
            onClose() {
              // 退出登录
            },
          });
        }, 1500);
      }
    });

    /**
     * 链接出问题时，内部进行重新链接，会出发这个事件
     */
    RongIMLib.addEventListener(Events.SUSPEND, () => {
      console.log("链接中断，SDK 会尝试重连，业务层无需关心");
      this.isConnected = false;
	  this.$store.saveSocketIsConnected(false);
    });

    // 收到消息
    RongIMLib.addEventListener(Events.MESSAGES, (messages) => {
      console.log(messages);
      if (messages.messages) {
        if (messages.messages.length > 0) {
          messages.messages.forEach((item) => {
            this.onMessage(item);
          });
        }
      }
    });
  }
  // 连接融云socket
  connect(token) {
    // console.log(token)
    return new Promise((resolve, reject) => {
      RongIMLib.connect(token).then((res) => {
		  console.log(res)
        if (res.code === RongIMLib.ErrorCode.SUCCESS) {
          console.log("链接成功, 链接用户 id 为: ", res.data.userId);
          resolve({ code: 1, msg: "链接成功" });
		  this.$store.saveLoginTime(new Date().getTime())
        } else {
          console.warn("链接失败, code:", res.code);
          this.reconnect();
          reject({ code: 0, msg: "链接失败" });
        }
		this.$store.saveSocketHaveLoaded(true)
      });
    });
  }
  // 重连
  reconnect() {
    clearInterval(this.timer);
    this.timer = setInterval(() => {
      // 重连超过5次且是断网的情况下 刷新页面
      countRefresh++;
      if (countRefresh >= 10) {
        window.location.reload();
      }
    }, this.timeOut);
  }
  // 断开链接
  disconnect() {
    return new Promise((resolve, reject) => {
      RongIMLib.disconnect().then((res) => {
        this.ownClose = true;
        console.log("断开链接成功");
        this.$store.saveLoginTime(0)
        this.destroy();
        this.isConnected = false;
        this.$store.saveSocketIsConnected(false);
        resolve({ code: 0, msg: "断开链接成功" });
      }).catch((error) => {
        console.log(error);
        resolve({ code: 1, msg: "断开链接失败" });
      });
    });
  }
  sendMessage(
    option = {
      content: "",
      roomId: "",
      gameId: "",
      type: "",
	  roleId: "",
      messageType: "",
      userId: "",
      userName: "",
      nickName: "",
      avatarPath: "",
      chatUserId: "",
      to: "",
    }
  ) {
    let chatType;
    if (option.type==="chat") {
      chatType = RongIMLib.ConversationType.GROUP;
    } else if (option.type==="groupchat") {
      chatType = RongIMLib.ConversationType.CHATROOM;
    }
    // console.log(option);
    // 指定消息发送的目标会话
    const conversation = {
      // targetId
      targetId:
        option.type==="chat"
          ? `${option.roomId}_${option.chatUserId}`
          : this.roomNo,
      conversationType: chatType,
    };
    let aseKey = 'sYO6HiZp3O1mCokG';
    let uuid = this.genId();
    let content = {};
    content.content = option.content;
    content.roomId = option.roomId;
    content.gameId = option.gameId;
    content.userName = option.userName;
    content.userId = option.userId;
    content.messageType = option.messageType;
    content.nickName = option.nickName;
    content.avatarPath = option.avatarPath;
    content.roleId = option.roleId;
    content.uuid = uuid;
    if (chatType===3) {
      content.to = option.to;
    }
    content = JSON.stringify(content);
    content = encrypt(content, aseKey);

    // 构建文本消息
    const message = new RongIMLib.TextMessage({ content: content });
    // 发送消息
    RongIMLib.sendMessage(conversation, message).then(({ code, data }) => {
      // 设置消息超时时间
      return new Promise((resolve) => {
        const sendtimer = setTimeout(() => {
          resolve({ code: -1, msg: "发送消息超时, 请重新发送" });
        }, 30000);
        if (code === 0) {
          console.log("消息发送成功：", data);
          let msgObj = this.formatMsgData(data);
          if (uuid === msgObj.uuid) {
            clearTimeout(sendtimer);
            this.$store.addMessage(msgObj);
            resolve({ code: 1, msg: "发送成功", data: message });
          }
        } else {
          console.log("消息发送失败：", code);
          console.log("消息发送失败：", data);
          clearTimeout(sendtimer);
          resolve({ code: -1, msg: "发送消息失败," + code });
        }
      });
    });
  }
  // 退出房间
  leaveRoom(roomNo, flag) {
    const leaveGroup = roomNo || this.roomNo;
    RongIMLib.quitChatRoom(leaveGroup).then((res) => {
      // 退出聊天室成功
      if (res.code === 0) {
        console.log("退出聊天室 " + leaveGroup);
      } else {
      }
    });
  }
  // 进入房间
  joinRoom(roomNo) {
    const joinGroup = roomNo;
    const count = 50;
    this.roomNo = joinGroup;
    return new Promise((resolve, reject) => {
      RongIMLib.joinExistChatRoom(joinGroup, {
        count: count,
      })
        .then((res) => {
          // 加入聊天室成功
          if (res.code === 0) {
            this.$store.changeMessage([]);
            console.log("加入聊天室成功" + joinGroup);
          } else {
            console.log(res.code, res.msg);
          }
          resolve(res)
        })
        .catch((error) => {
          console.log(error);
          reject(error)
        });
    });
  }
  // 接收到的私聊 群聊
  onMessage(msg) {
    try {
      let aseKey = 'sYO6HiZp3O1mCokG';
      // 解密后的数据
      let decryptData = decrypt(msg.content.content || msg.content.message, aseKey);
      let data;
      let msgobj;
      try {
        data = JSON.parse(decryptData);
      } catch (err) {}
      // data json解析成功即会员发的消息 否则gzip解压
      if (data) {
        msgobj = data;
      } else {
        msgobj = JSON.parse(gunzip(decryptData));
      }
      msgobj.uuid = msgobj.uuid ? msgobj.uuid : msg.messageUId;
      msgobj.time = msg.sentTime;
      // msgobj.chatType = msg.conversationType===3 ? "chat" : "groupchat";
	  msgobj.chatType = "groupchat";
      // msgobj.userName = msgobj.userName.toLowerCase();
      console.log(msgobj);
      // 群聊
	  // NORMAL(-1, "普通消息"),
	  // SYSTEM(0, "系统消息"),
	  // BUY_ORDER(1, "买家下单发送确认消息"),
	  // SELLER_ACCEPT_INFO(2, "卖家同意交易发送截图信息"),
	  // PAY_INFO(3, "买家已付款,发送转账截图信息"),
	  // SHIP_INFO(4, "发货信息"),
	  // IMG(7, "图片"),
	  // MERGE_MESSAGE(5, "合并消息"),
	  
	  // MESSAGE_TYPE_LOGIN_OUT(“6”,“用户推出登录消息“),
	  if (msgobj.messageType === '6' && this.$store.loginTime && (this.$store.loginTime < msgobj.time)) {
        Toast({
          message: msgobj.content,
          duration: 3000,
          onClose() {
            setTimeout(()=>{
              this.$store.logout();
            },500)
          },
        });
	  }
	  // MESSAGE_TYPE_LOGIN_OUT(“16”,“多端登录“),
	  if (msgobj.messageType === '16' && this.$store.loginTime && (this.$store.loginTime < msgobj.time)) {
		  Toast({
        message: msgobj.content,
        duration: 3000,
        onClose() {
          setTimeout(()=>{
            this.$store.logout();
          },500)
        },
      });
	  }
	  // 14 仲裁订单 转审核中 （权限客服收推送）
	  if (msgobj.messageType === '14' && this.$store.loginTime && (this.$store.loginTime < msgobj.time)) {
	    if(this.$store.countArbitrateInfo){
	  	this.$store.saveCountArbitrateInfo({
	  	  sum: this.$store.countArbitrateInfo.sum+1
	  	})
	    }else{
	  	  this.$store.saveCountArbitrateInfo({
	  		sum: 1
	  	  })
	    }
	  }
	  // 15 仲裁订单 转审核中 （风控客服收推送）
	  if (msgobj.messageType === '15' && this.$store.loginTime && (this.$store.loginTime < msgobj.time)) {
	    if(this.$store.countArbitrateInfo){
	  	this.$store.saveCountArbitrateInfo({
	  	  sum: this.$store.countArbitrateInfo.sum+1
	  	})
	    }else{
	  	  this.$store.saveCountArbitrateInfo({
	  		sum: 1
	  	  })
	    }
	  }  
	  
		// 11 会员
		if (msgobj.messageType === '11' && this.$store.permissions.indexOf("12")!==-1 && this.$store.loginTime && (this.$store.loginTime < msgobj.time)) {
		  if(this.$store.notReviewedOrder){
			this.$store.saveNotReviewedOrder({
			  ...this.$store.notReviewedOrder,
			  memberRecharge: this.$store.notReviewedOrder.memberRecharge+1
			})
		  }else{
			  this.$store.saveNotReviewedOrder({
				memberRecharge: 1
			  })
		  }
		}
		// 12 商户存款 
		if (msgobj.messageType === '12' && this.$store.permissions.indexOf("10")!==-1 && this.$store.loginTime && (this.$store.loginTime < msgobj.time)) {
		  if(this.$store.notReviewedOrder){
			this.$store.saveNotReviewedOrder({
			  ...this.$store.notReviewedOrder,
			  merchantRecharge: this.$store.notReviewedOrder.merchantRecharge+1
			})
		  }else{
			  this.$store.saveNotReviewedOrder({
				merchantRecharge: 1
			  })
		  }
		}
		// 13 商户提款
		if (msgobj.messageType === '13' && this.$store.permissions.indexOf("11")!==-1 && this.$store.loginTime && (this.$store.loginTime < msgobj.time)) {
		  if(this.$store.notReviewedOrder){
			this.$store.saveNotReviewedOrder({
			  ...this.$store.notReviewedOrder,
			  merchantDraw: this.$store.notReviewedOrder.merchantDraw+1
			})
		  }else{
			  this.$store.saveNotReviewedOrder({
				merchantDraw: 1
			  })
		  }
		}  
	  
      if (msg.conversationType===4) {
		this.$store.addMessage(msgobj);
      }
    } catch (err) {
      console.log(err);
      return true;
    }
    return true;
  }
  // 处理聊天数据
  formatMsgData(msg) {
    if (typeof msg === "object") {
      let aseKey = 'sYO6HiZp3O1mCokG';
      let msgobj = JSON.parse(decrypt(msg.content.content, aseKey));
      msgobj.uuid = msgobj.uuid ? msgobj.uuid : this.genId();
      msgobj.time = msg.sentTime;
      if (msg.conversationType===3) {
        // 不为0时新增chatname
        if (msgobj.messageType !== 0) {
          msgobj.chatname = msgobj.userName.toLowerCase();
        }
      }
      msgobj.chatType = msg.conversationType===3 ? "chat" : "groupchat";
      return msgobj;
    } else {
      return {};
    }
  }
  // 生成消息id
  genId() {
    return `id-${Date.now()}-${Math.random().toString(16).substr(2)}`;
  }
}

export default {
  install(Vue, store, router) {
    const bus = (Vue.prototype.$bus = Vue.$bus = new Vue());
    Vue.prototype.$imsocket = new RySocket(store, router, bus || Vue.$bus);
  },
};
